class LoginStars {

    constructor(stars, opts) {
        this.stars = stars;
        this.user_name = stars.projectName + '-userName';
        this.login_token = stars.projectName + '-login_token';
        this.removeLoginInfo();
        this.permissionUrl = opts.permissionUrl;
        this.loginUrl = opts.loginUrl;
        this.indexUrl = opts.indexUrl;
        $.getScript(this.stars.contentPath + '/webjars/starsjs/lib/galaxy.js', () => new Galaxy($('.base-bg'), $('#galaxy')[0]));
        $.getScript(this.stars.contentPath + '/webjars/starsjs/lib/md5.js', () => this.signBtn = $('.sign-btn button').on('click', () => this.submit()));
    }

    submit() {
        var userName = $('input[type="text"]').val();
        var password = $('input[type="password"]').val();
        if (userName == '' || password == '') {
            this.stars.showErrorNoty({
                progressBar: false,
                timeout: 1500,
                text: 'UserName and password cannot be empty!'
            });
            return;
        }
        this.stars.setCycleTextWithPoint(this.signBtn, 'Signing');
        this.signBtn.off('click').addClass('disabled');
        this.stars.ajaxPost({
            url: this.permissionUrl,
            data: {
                userName: userName,
                password: CryptoJS.MD5(password).toString()
            },
            success: (dataMsg) => {
                if (dataMsg.status == 'success') {
                    this.setLoginInfo(dataMsg.data);
                    this.toIndex();
                } else {
                    this.stars.removeCycle(this.signBtn);
                    this.signBtn.on('click', () => this.submit(this.signBtn)).removeClass('disabled');
                    setTimeout(() => {
                        this.stars.showErrorNoty({
                            progressBar: false,
                            timeout: 1500,
                            text: 'UserName or password is not correct!'
                        });
                    }, 500);
                }
            }
        });
    }

    getAxiosPostHeader() {
        return {
            headers: {
                'user-name': this.stars.getAttribute(this.user_name),
                'login-token': this.stars.getAttribute(this.login_token)
            }
        };
    }

    setLoginInfo(data) {
        this.stars.setAttribute(this.user_name, data.userName);
        this.stars.setAttribute(this.login_token, data.loginToken);
    }

    removeLoginInfo() {
        this.stars.removeAttribute(this.user_name);
        this.stars.removeAttribute(this.login_token);
    }

    toLogin() {
        window.location.href = this.stars.contentPath + this.loginUrl;
    }

    toIndex() {
        window.location.href = this.stars.contentPath + this.indexUrl;
    }
}